package com.zsc.newbuds.component;


import com.zsc.newbuds.entity.Admin;
import com.zsc.newbuds.service.impl.AdminServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author D
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    AdminServiceImpl userService;


    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("授权");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();
        Admin currentAdmin = (Admin) subject.getPrincipal();

        System.out.println("职位"+currentAdmin.getPosition());
        simpleAuthorizationInfo.addStringPermission(currentAdmin.getPosition());


        return simpleAuthorizationInfo;

    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("认证");
        UsernamePasswordToken userToken =(UsernamePasswordToken) authenticationToken;

        Admin admin = userService.getAdminByAccount(userToken.getUsername());

        if(admin == null){
            return null;
        }

        return new SimpleAuthenticationInfo(admin,admin.getPassword(),"");
    }

}
